<?php
// +----------------------------------------------------------------------
// | 名片应用
// | Author: 张亚 < zhyacn@gmail.com>
// | Time: 2017-11-26
// +----------------------------------------------------------------------
namespace app\businesscard\controller;

use app\businesscard\model\BusinessCardModel;
use app\businesscard\model\BusinessCategoryModel;
use app\businesscard\service\CardService;
use cmf\controller\HomeBaseController;
use think\Db;

class CardController extends HomeBaseController {

	public function index() {
		$cardService = new CardService();

		$cardId = $this->request->param('id', 0, 'intval');
		$card = $cardService->publishedCard($cardId);

		if (empty($cardId)) {
			abort(404, '名片不存在!');
		}
		//刷新浏览数
		$cardService->refreshCardHits($cardId);

		//查询行业
		$this->assign('card', $card);

		return $this->fetch(":card");
	}

	// 文章点赞
	public function doLike() {
		$this->checkUserLogin();
		$cardId = $this->request->param('id', 0, 'intval');

		$canLike = cmf_check_user_action("cards$cardId", 1);

		if ($canLike) {
			Db::name('business_card')->where(['id' => $cardId])->setInc('card_like');

			$this->success("赞好啦！");
		} else {
			$this->error("您已赞过啦！");
		}
	}

	public function my() {
		$this->checkUserLogin();
		//获取登录会员信息
		$user_id = cmf_get_current_user_id();

		$this->assign('user_id', $user_id);
		$param['user_id'] = $user_id;

		$cardService = new CardService();
		$data = $cardService->adminCardList($param);

		$data->appends($param);

		$this->assign(cmf_get_current_user());
		$this->assign('cards', $data->items());
		$this->assign('page', $data->render());

		return $this->fetch('user/my');
	}

	//用户添加
	public function add() {
		$this->checkUserLogin();
		return $this->fetch('user/add');
	}

	public function addCard() {
		if ($this->request->isPost()) {
			$data = $this->request->param();
			$post = $data['post'];
			$result = $this->validate($post, 'AdminCard');
			if ($result !== true) {
				$this->error($result);
			}

			$businessCardModel = new BusinessCardModel();

			if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
				$data['post']['more']['photos'] = [];
				foreach ($data['photo_urls'] as $key => $url) {
					$photoUrl = cmf_asset_relative_url($url);
					array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
				}
			}

			if (!empty($data['file_names']) && !empty($data['file_urls'])) {
				$data['post']['more']['files'] = [];
				foreach ($data['file_urls'] as $key => $url) {
					$fileUrl = cmf_asset_relative_url($url);
					array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
				}
			}

			//前台用户自行添加名片时，作者是当前登录的用户
			$data['post']['user_id'] = cmf_get_current_user_id();

			$businessCardModel->adminAddCard($data['post'], $data['post']['categories']);

			$this->success('添加成功!', url('businesscard/Card/index', ['id' => $businessCardModel->id]));
		}
	}

	public function select() {
		$ids = $this->request->param('ids');
		$selectedIds = explode(',', $ids);
		$businessCategoryModel = new BusinessCategoryModel();

		$tpl = <<<tpl
<tr class='data-item-tr'>
    <td>
        <input type='checkbox' class='js-check' data-yid='js-check-y' data-xid='js-check-x' name='ids[]'
                               value='\$id' data-name='\$name' \$checked>
    </td>
    <!--<td>\$id</td>
    <td>\$spacer <a href='\$url' target='_blank'>\$name</a></td>
    <td>\$description</td>-->
    <td>\$spacer \$name</td>
</tr>
tpl;

		$categoryTree = $businessCategoryModel->adminCategoryTableTree($selectedIds, $tpl);

		$where = ['delete_time' => 0];
		$categories = $businessCategoryModel->where($where)->select();

		$this->assign('categories', $categories);
		$this->assign('selectedIds', $selectedIds);
		$this->assign('categories_tree', $categoryTree);
		return $this->fetch('user/select');
	}

	/**
	 * 编辑名片
	 */
	public function edit() {
		$this->checkUserLogin();
		$id = $this->request->param('id', 0, 'intval');

		$businessCardModel = new BusinessCardModel();
		$post = $businessCardModel->where('id', $id)->find();
		$postCategories = $post->categories()->alias('a')->column('a.name', 'a.id');
		$postCategoryIds = implode(',', array_keys($postCategories));

		$this->assign('post', $post);
		$this->assign('post_categories', $postCategories);
		$this->assign('post_category_ids', $postCategoryIds);

		return $this->fetch('user/edit');
	}

	/**
	 * 编辑名片提交
	 */
	public function editCard() {

		if ($this->request->isPost()) {
			$data = $this->request->param();
			$post = $data['post'];
			$result = $this->validate($post, 'AdminCard');
			if ($result !== true) {
				$this->error($result);
			}

			$businessCardModel = new BusinessCardModel();

			if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
				$data['post']['more']['photos'] = [];
				foreach ($data['photo_urls'] as $key => $url) {
					$photoUrl = cmf_asset_relative_url($url);
					array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
				}
			}

			if (!empty($data['file_names']) && !empty($data['file_urls'])) {
				$data['post']['more']['files'] = [];
				foreach ($data['file_urls'] as $key => $url) {
					$fileUrl = cmf_asset_relative_url($url);
					array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
				}
			}

			$businessCardModel->adminEditCard($data['post'], $data['post']['categories']);

			$hookParam = [
				'is_add' => false,
				'card' => $data['post'],
			];
			hook('portal_admin_after_save_card', $hookParam);

			$this->success('保存成功!');

		}
	}

	/**
	 * 名片删除
	 */
	public function delete() {
		$param = $this->request->param();
		$businessCardModel = new BusinessCardModel();

		if (isset($param['id'])) {
			$id = $this->request->param('id', 0, 'intval');
			$result = $businessCardModel->where(['id' => $id])->find();
			$data = [
				'object_id' => $result['id'],
				'create_time' => time(),
				'table_name' => 'business_card',
				'name' => $result['name'],
			];
			$resultPortal = $businessCardModel
				->where(['id' => $id])
				->update(['delete_time' => time()]);
			if ($resultPortal) {
				Db::name('portal_category_post')->where(['post_id' => $id])->update(['status' => 0]);
				Db::name('portal_tag_post')->where(['post_id' => $id])->update(['status' => 0]);

				Db::name('recycleBin')->insert($data);
			}
			$this->success("删除成功！", '');

		}

		if (isset($param['ids'])) {
			$ids = $this->request->param('ids/a');
			$recycle = $businessCardModel->where(['id' => ['in', $ids]])->select();
			$result = $businessCardModel->where(['id' => ['in', $ids]])->update(['delete_time' => time()]);
			if ($result) {
				foreach ($recycle as $value) {
					$data = [
						'object_id' => $value['id'],
						'create_time' => time(),
						'table_name' => 'business_card',
						'name' => $value['name'],
					];
					Db::name('recycleBin')->insert($data);
				}
				$this->success("删除成功！", '');
			}
		}
	}
}
